package cc.sunni.sell.controller;

import cc.sunni.sell.entity.ProductCategory;
import cc.sunni.sell.entity.ProductInfo;
import cc.sunni.sell.service.ProductCategoryService;
import cc.sunni.sell.service.ProductInfoService;
import cc.sunni.sell.utils.R;
import cc.sunni.sell.vo.ProductInfoVO;
import cc.sunni.sell.vo.ProductVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author jl
 * @since 2021/1/17 21:15
 */
@RestController
@RequestMapping("/buyer/product")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class BuyerProductController {
    private final ProductInfoService productInfoService;
    private final ProductCategoryService productCategoryService;

    @GetMapping("/list")
    @Cacheable(cacheNames = "product#7200", key = "#root.methodName", unless = "#result.get('success')==false")
    public R list() {
        // 查询所有上架的商品
        List<ProductInfo> productInfoUps = productInfoService.getProductInfoUp();
        // 过滤出上架商品的类目
        List<Integer> categoryIds = productInfoUps.stream().map(ProductInfo::getCategoryType).collect(Collectors.toList());
        List<ProductCategory> productCategories = productCategoryService.list(new LambdaQueryWrapper<ProductCategory>().in(ProductCategory::getCategoryId, categoryIds));
        // 封装VO
        Map<Integer, List<ProductInfo>> productInfoMap = productInfoUps.stream().collect(Collectors.groupingBy(ProductInfo::getCategoryType));
        List<ProductVO> productVOS = new ArrayList<>();
        for (ProductCategory productCategory : productCategories) {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryType(productCategory.getCategoryType());
            productVO.setCategoryName(productCategory.getCategoryName());

            List<ProductInfo> productInfos = productInfoMap.get(productCategory.getCategoryId());
            List<ProductInfoVO> productInfoVOS = productInfos.stream().map(e -> {
                ProductInfoVO productInfoVO = new ProductInfoVO();
                BeanUtils.copyProperties(e, productInfoVO);
                return productInfoVO;
            }).collect(Collectors.toList());
            productVO.setProductInfoVOList(productInfoVOS);
            productVOS.add(productVO);
        }

        return R.ok(productVOS);
    }
}
